package com.geekchique.runningbuddy.service;

import java.util.List;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Intent;
import android.location.LocationManager;
import android.location.LocationProvider;
import android.os.DeadObjectException;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.RemoteCallbackList;
import android.util.Log;
import android.widget.Toast;

import com.geekchique.runningbuddy.R;
import com.geekchique.runningbuddy.activity.Stopwatch;
import com.geekchique.runningbuddy.activity.stopwatch.StopwatchThread;
import com.geekchique.runningbuddy.provider.ActivityID;

public class RemoteStopClockService extends Service
{
	final RemoteCallbackList<IRemoteServiceCallback> registeredCallbacks  = new RemoteCallbackList<IRemoteServiceCallback>();
    private NotificationManager mNM;
    protected StopwatchThread timerRunnerThread;
	protected LocationManager locationManager = null;
	private static final String PROVIDERNAME = "testjog";
	private static final String TAG = "[RBuddy]: " + RemoteStopClockService.class.getName();
    protected LocationProvider provider;

	@Override
    protected void onCreate() {

		mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
    	timerRunnerThread = new StopwatchThread(messageHandler);
		timerRunnerThread.start();

        showNotification();
        messageHandler.sendEmptyMessage(ActivityID.UPDATESTOPCLOCK);
    }

    private final Handler messageHandler = new Handler() {
    	@Override
    	public void handleMessage(Message msg) {

        	switch (msg.what) {
        		case ActivityID.UPDATESTOPCLOCK: {
                    final int registered = registeredCallbacks.beginBroadcast();
                    for (int i=0; i<registered; i++) {
                    	try {
                        	registeredCallbacks.getBroadcastItem(i).updatedStopwatch(timerRunnerThread.getElapsedTime());
                        } catch (DeadObjectException e) {
                        	Log.e(TAG, "Remote service recieved dead object.");
                        }
                    }

                    registeredCallbacks.finishBroadcast();
                    sendMessageDelayed(obtainMessage(ActivityID.UPDATESTOPCLOCK), 1*100);

                }
        		break;

        		default:
                    super.handleMessage(msg);
            }
        }
    };



    /**
	 * IRemoteStopClockServiceInterface is defined through IDL
	 */
	private final IRemoteStopClockService.Stub messageBinder = new IRemoteStopClockService.Stub() {
		public void registerStopClockUpdateListener(IRemoteServiceCallback cb)
				throws DeadObjectException {
			if (cb != null)
				registeredCallbacks.register(cb);
		}

		public void unregisterStopClockUpdateListener(IRemoteServiceCallback cb)
				throws DeadObjectException {
			if (cb != null)
				registeredCallbacks.unregister(cb);
		}
	};





	public void startTrackingRoute() {
		final long MINIMUM_DISTANCECHANGE_FOR_UPDATE = 25; // in Meters
		final long MINIMUM_TIME_BETWEEN_UPDATE = 5000; // in Milliseconds
		List<LocationProvider> locProviders = locationManager.getProviders();
		provider = locProviders.get(0);
		provider = locationManager.getProvider(PROVIDERNAME);

		this.locationManager.requestUpdates(provider, MINIMUM_TIME_BETWEEN_UPDATE,	MINIMUM_DISTANCECHANGE_FOR_UPDATE, new Intent(ActivityID.MY_LOCATION_CHANGED_ACTION));
	}

	public void stopTrackingRoute() {
		this.locationManager.removeUpdates(new Intent(ActivityID.MY_LOCATION_CHANGED_ACTION));
	}















	private void showNotification() {
		Intent contentIntent = new Intent(this, Stopwatch.class);
	    Intent appIntent = new Intent(this, Stopwatch.class);
	    CharSequence text = getText(R.string.local_service_started);

	    mNM.notify(
	    		R.string.local_service_started, // we use a string id because it is a unique
	                                                  // number.  we use it later to cancel the
	                                                  // notification
	               new Notification(
	                   this,                        // our context
	                   R.drawable.stat_sample,                      // the icon for the status bar
	                   text,                  // the text to display in the ticker
	                   System.currentTimeMillis(),  // the timestamp for the notification
	                   getText(R.string.local_service_started),               // the title for the notification
	                   text,                        // the details to display in the notification
	                   contentIntent,               // the contentIntent (see above)
	                   R.drawable.stat_sample,  // the app icon
	                   getText(R.string.local_service_started), // the name of the app
	                   appIntent));                 // the appIntent (see above)
	}

	@Override
	public IBinder onBind(Intent arg0) {
		return messageBinder;
	}

	@Override
	protected void onDestroy() {
	    mNM.cancel(R.string.local_service_started);
		Toast.makeText(this, getText(R.string.local_service_stopped), Toast.LENGTH_SHORT).show();

		registeredCallbacks.kill();
		messageHandler.removeMessages(ActivityID.UPDATESTOPCLOCK);
		timerRunnerThread.stop();
	}

}

